<template>
    <div>
        <div class="my-top">
            <p>评论区</p>
        </div>
        <div v-clickoutside="hideReplyBtn"
             @click="inputFocus"
             class="my-reply">
            <div class="reply-info">
                <div class="reply-input"
                     tabindex="0"
                     contenteditable="true"
                     id="replyInput"
                     spellcheck="false"
                     placeholder="请分享你的留言..."
                     @focus="showReplyBtn"
                     @input="onDivInput($event)">
                </div>
            </div>
            <div class="reply-btn-box"
                 v-show="btnShow">
                <el-button class="reply-btn"
                           size="medium"
                           @click="cancelSendComment"
                           type="warning">取消</el-button>
                <el-button class="reply-btn"
                           size="medium"
                           @click="sendComment"
                           type="primary">发表评论</el-button>
            </div>
        </div>
        <div v-for="(item,i) in comments"
             :key="i"
             class="author-title reply-father">
            <!-- <el-avatar class="header-img" :size="40" :src="item.headImg"></el-avatar> -->
            <div class="author-info">
                <span class="author-name">{{item.name}}</span>
                <span class="author-time">{{item.time}}</span>
            </div>
            <div class="icon-btn">
                <span @click="showReplyInput(i,item.name,item.id,item.ct_id,'',item.id,item.a_id,item.ct_id,1,item.name,item.id,)">
                    <el-button class="add-border "
                               size="small"
                               icon="el-icon-s-comment">
                        <p class="add-listname">回复</p>
                    </el-button>
                </span>
            </div>
            <div class="talk-box">
                <p>
                    <!-- <span>:</span> -->
                    <span class="reply"
                          v-html="item.comment">
                        {{item.comment}}</span>
                </p>
            </div>
            <div class="reply-box">
                <div v-for="(reply,j) in item.reply"
                     :key="j"
                     class="author-title">
                    <!-- <el-avatar class="header-img" :size="40" :src="reply.fromHeadImg"></el-avatar> -->
                    <div class="author-info">
                        <span class="author-name">{{reply.from}}</span>
                        <span class="author-time">{{reply.time}}</span>
                    </div>
                    <div class="icon-btn">
                        <span @click="showReplyInput(i,reply.from,reply.fromId,reply.ct_id,'',reply.fromId, reply.a_id,reply.hf_id,2,reply.to,reply.toId)">
                            <!-- <i class="iconfont el-icon-s-comment"></i>{{reply.commentNum}}-->
                            <el-button class="add-border-reply "
                                       size="small"
                                       icon="el-icon-s-comment">
                                <p class="add-listname">回复</p>
                            </el-button>
                        </span>
                        <!-- <i class="iconfont el-icon-caret-top"></i>{{reply.like}} -->
                    </div>
                    <div class="talk-box">
                        <p>
                            <span>回复 {{reply.to}}:</span>
                            <span class="reply"
                                  v-html="reply.comment">
                                {{reply.comment}} </span>
                        </p>
                    </div>
                    <div class="reply-box">
                    </div>
                </div>
            </div>
            <div v-show="_inputShow(i)"
                 class="my-reply my-comment-reply">
                <!-- <el-avatar class="header-img" :size="40" :src="myHeader"></el-avatar> -->
                <div class="reply-info-se">
                    <div tabindex="0"
                         contenteditable="true"
                         spellcheck="false"
                         placeholder="回复，友好交流的开始..."
                         @input="onDivInput($event)"
                         class="reply-input reply-comment-input"></div>
                </div>
                <div class=" reply-btn-box">
                    <el-button class="reply-btn"
                               size="medium"
                               @click="cancelSeSendComment"
                               type="warning">取消</el-button>
                    <el-button class="reply-btn"
                               size="medium"
                               @click="sendCommentReply()"
                               type="primary">回复评论</el-button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { throttle } from "../../ElementUI/public.js";
const clickoutside = {
    // 初始化指令
    bind(el, binding, vnode) {
        function documentHandler(e) {
            // 这里判断点击的元素是否是本身，是本身，则返回
            if (el.contains(e.target)) {
                return false;
            }
            // 判断指令中是否绑定了函数
            if (binding.expression) {
                // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
                binding.value(e);
            }
        }
        // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
        el.vueClickOutside = documentHandler;
        document.addEventListener('click', documentHandler);
    },
    update() { },
    unbind(el, binding) {
        // 解除事件监听
        document.removeEventListener('click', el.vueClickOutside);
        delete el.vueClickOutside;
    },
};
export default {
    name: 'ArticleComment',
    data() {
        return {
            btnShow: false,
            index: '0',
            replyComment: '',
            canreplyComment: '',
            myName: 'Lana',
            myHeader: 'https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg',
            myId: 19870621,
            to: '',
            toId: -1,
            comments: [
                {
                    name: 'Lana Del Rey',
                    id: 19870621,
                    headImg: 'https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg',
                    comment: '我发布一张新专辑Norman Fucking Rockwell,大家快来听啊',
                    time: '2019年9月16日 18:43',
                    commentNum: 2,
                    like: 15,
                    inputShow: false,
                    reply: [
                        {
                            from: 'Taylor Swift',
                            fromId: 19891221,
                            fromHeadImg: 'https://ae01.alicdn.com/kf/H94c78935ffa64e7e977544d19ecebf06L.jpg',
                            to: 'Lana Del Rey',
                            toId: 19870621,
                            comment: '我很喜欢你的新专辑！！',
                            time: '2019年9月16日 18:43',
                            commentNum: 1,
                            like: 15,
                            inputShow: false
                        },
                        {
                            from: 'Ariana Grande',
                            fromId: 1123,
                            fromHeadImg: 'https://ae01.alicdn.com/kf/Hf6c0b4a7428b4edf866a9fbab75568e6U.jpg',
                            to: 'Lana Del Rey',
                            toId: 19870621,
                            comment: '别忘记宣传我们的合作单曲啊',
                            time: '2019年9月16日 18:43',
                            commentNum: 0,
                            like: 5,
                            inputShow: false

                        }
                    ]
                },
                {
                    name: 'Taylor Swift',
                    id: 19891221,
                    headImg: 'https://ae01.alicdn.com/kf/H94c78935ffa64e7e977544d19ecebf06L.jpg',
                    comment: '我发行了我的新专辑Lover',
                    time: '2019年9月16日 18:43',
                    commentNum: 1,
                    like: 5,
                    inputShow: false,
                    reply: [
                        {
                            from: 'Lana Del Rey',
                            fromId: 19870621,
                            fromHeadImg: 'https://ae01.alicdn.com/kf/Hd60a3f7c06fd47ae85624badd32ce54dv.jpg',
                            to: 'Taylor Swift',
                            toId: 19891221,
                            comment: '新专辑和speak now 一样棒！',
                            time: '2019年9月16日 18:43',
                            commentNum: 25,
                            like: 5,
                            inputShow: false

                        }
                    ]
                },
                {
                    name: 'Norman Fucking Rockwell',
                    id: 20190830,
                    headImg: 'https://ae01.alicdn.com/kf/Hdd856ae4c81545d2b51fa0c209f7aa28Z.jpg',
                    comment: 'Plz buy Norman Fucking Rockwell on everywhere',
                    time: '2019年9月16日 18:43',
                    commentNum: 0,
                    like: 5,
                    inputShow: false,
                    reply: []
                },
            ],
            textid: "",
            accessId: 0,
            accessName: "",
            commentId: 0,

            repleM_id: "",
            Content: "",
            repleA_id: "",
            repleCt_id: "",
            repleHf_id: "",
            repleType: "",
            repleTo: "",
            repleToId: "",
        }
    },
    directives: { clickoutside },
    created() {
        this.accessId = localStorage.getItem('accessId');
        this.myName = localStorage.getItem('accessName');
        this.textid = sessionStorage.getItem('Details');
        //获取评论列表
        this.getArtcomlist(this.textid, 1, 100);
    },
    methods: {
        //获取评论列表
        getArtcomlist(a_id, page, limit) {
            let _this = this;
            _this.comments = []
            let Url = "/artcomlist?a_id=" + a_id + "&page=" + page + "&limit=" + limit
            let Params = {};
            _this.$https.fetchGet(Url, Params).then(res => {
                let resdata = res.data;
                switch (resdata.code) {
                    case 1000:
                        let adddata = resdata.data
                        switch (adddata.current_page) {
                            case 1:
                                let commentsdata = adddata.data;
                                for (var i = 0; i < commentsdata.length; i++) {
                                    let replylist = [];
                                    for (var j = 0; j < commentsdata[i].reply.length; j++) {
                                        let reg2 = new RegExp('<div><br></div>', "g")
                                        let ChangeReplycomment = commentsdata[i].reply[j].re_content.replace(reg2, "").replace(/&nbsp;/ig, "");
                                        replylist.push({
                                            from: commentsdata[i].reply[j].has_one_member.name,//回复人姓名
                                            fromId: commentsdata[i].reply[j].has_one_member.m_id,//回复人id
                                            to: commentsdata[i].reply[j].to_one_member.name,//被回复人姓名
                                            toId: commentsdata[i].reply[j].to_one_member.m_id,//被回复人id
                                            comment: ChangeReplycomment,//回复内容
                                            time: commentsdata[i].reply[j].created_at,//回复时间
                                            a_id: commentsdata[i].reply[j].a_id,//文章id
                                            ct_id: commentsdata[i].reply[j].ct_id,//评论id
                                            hf_id: commentsdata[i].reply[j].re_id,//回复id
                                            type: commentsdata[i].reply[j].type,//1回复评论    2回复用户回复
                                            commentNum: 1,
                                            like: 15,
                                            inputShow: false
                                        })
                                    }
                                    let reg = new RegExp('<div><br></div>', "g")
                                    let Changecomment = commentsdata[i].content.replace(reg, "").replace(/&nbsp;/ig, "");
                                    this.comments.push({
                                        name: commentsdata[i].has_one_member.name,
                                        id: commentsdata[i].has_one_member.m_id,
                                        a_id: commentsdata[i].a_id,
                                        ct_id: commentsdata[i].ct_id,
                                        comment: Changecomment,
                                        time: commentsdata[i].created_at,
                                        commentNum: 2,
                                        like: 15,
                                        inputShow: false,
                                        reply: replylist
                                    });
                                }
                                break;
                        }
                        break;
                    case 1002:

                        break
                }
            });
        },
        //评论
        inputFocus() {
            var replyInput = document.getElementById('replyInput');
            replyInput.style.padding = "8px 8px"
            replyInput.style.border = "2px solid blue"
            replyInput.focus()
        },
        //按钮隐现
        showReplyBtn() {
            this.btnShow = true
            if(this.index !=0){
               this.comments[this.index].inputShow = false
            }
        },
        hideReplyBtn() {
            this.btnShow = false
            replyInput.style.padding = "10px"
            replyInput.style.border = "none"
        },
        //触发回复机制
        showReplyInput(i, name, id, ct_id, content, m_id, a_id, hf_id, type, to, toId) {
            this.repleCt_id = ct_id;
            this.Content = content;
            this.repleM_id = m_id;
            this.repleA_id = a_id;
            this.repleHf_id = hf_id;
            this.repleType = type;
            this.repleTo = to;
            this.repleToId = toId;
            if (this.comments[i].inputShow == false) {
                this.comments[this.index].inputShow = false
                this.index = i
                this.comments[i].inputShow = true
                this.to = name
                this.toId = id
            }
            else {
                if (this.index == i) {
                    if (this.toId == id) {
                        this.comments[i].inputShow = false
                        this.index = i
                        this.comments[i].inputShow = false
                        this.to = name
                        this.toId = id
                    }
                    else {
                        this.comments[this.index].inputShow = false
                        this.index = i
                        this.comments[i].inputShow = true
                        this.to = name
                        this.toId = id
                    }
                }
                else {
                    this.comments[this.index].inputShow = false
                    this.index = i
                    this.comments[i].inputShow = true
                    this.to = name
                    this.toId = id
                }
            }
        },
        _inputShow(i) {
            return this.comments[i].inputShow
        },
        //一级评论
        sendComment: throttle(function () {
            let _this = this;
            if (localStorage.getItem("accessId") && (new Date().getTime() - localStorage.getItem("loginTime")) < 12 * 60 * 60 * 1000) {
                if (!_this.replyComment) {
                    _this.$message({
                        showClose: true,
                        type: 'warning',
                        message: '评论不能为空'
                    })
                } else {
                    _this.btnShow = false
                    let Url = "/artcomment"
                    let Params = {
                        a_id: _this.textid,
                        //a_id: 66,
                        content: _this.replyComment,
                        m_id: _this.accessId
                    };
                    _this.$https.fetchPost(Url, Params).then(res => {
                        let resdata = res.data;
                        switch (resdata.code) {
                            case 1000:
                                _this.showError("success", "评论发布成功");
                                //获取评论列表
                                //this.getArtcomlist(this.textid, 1, 100);
                                _this.commentId = resdata.data.ct_id//评论id

                                let a = {}
                                let input = document.getElementById('replyInput')
                                let timeNow = new Date().getTime();
                                let time = _this.dateStr(timeNow);

                                a.name = _this.myName//用户名称
                                a.id = _this.accessId //用户id
                                a.a_id = _this.textid//文章id
                                a.ct_id = _this.commentId//评论id

                                let reg = new RegExp('<div><br></div>', "g")
                                let Changecomment = _this.replyComment.replace(reg, "").replace(/&nbsp;/ig, "");
                                a.comment = Changecomment//回复内容

                                // a.headImg = this.myHeader
                                a.time = time//回复时间
                                a.commentNum = 0
                                a.like = 0
                                a.reply = []
                                a.inputShow = false

                                _this.comments.push(a)
                                _this.replyComment = ''
                                input.innerHTML = '';
                                break;
                            case 2000:
                                _this.showError("error", resdata.msg + "，请重新输入");
                                break;
                        }
                    });
                }
            }
            else {
                _this.PayOpen()
            }
        }, 2000),
        //二级回复评论
        sendCommentReply: throttle(function () {
            let _this = this;
            if (localStorage.getItem("accessId") && (new Date().getTime() - localStorage.getItem("loginTime")) < 12 * 60 * 60 * 1000) {
                if (!_this.replyComment) {
                    _this.$message({
                        showClose: true,
                        type: 'warning',
                        message: '评论不能为空'
                    })
                } else {
                    _this.btnShow = false
                    _this.comments[_this.index].inputShow = false
                    let Url = "/artrepcomment"
                    let Params = {
                        a_id: _this.textid,//文章id
                        ct_id: _this.repleCt_id,//评论id
                        content: _this.replyComment,//回复内容
                        m_id: _this.accessId,//当前用户id
                        hf_id: _this.repleHf_id,//回复目标id
                        type: _this.repleType,// 回复类型  1回复评论2回复用户回复
                    };
                    _this.$https.fetchPost(Url, Params).then(res => {
                        let resdata = res.data;
                        switch (resdata.code) {
                            case 1000:
                                _this.showError("success", "评论发布成功");
                                let a = {}
                                let timeNow = new Date().getTime();
                                let time = _this.dateStr(timeNow);
                                //let time = timeNow;

                                a.from = _this.myName//回复人姓名
                                a.fromId = _this.accessId//回复人id
                                a.to = _this.repleTo//被回复人姓名
                                a.toId = _this.repleToId//被回复人id
                                //a.fromHeadImg = _this.myHeader

                                let reg = new RegExp('<div><br></div>', "g")
                                let Changecomment = _this.replyComment.replace(reg, "").replace(/&nbsp;/ig, "");
                                a.comment = Changecomment//回复内容
                                // a.comment = _this.replyComment//回复内容
                                a.time = time//回复时间
                                a.a_id = _this.textid//文章id
                                a.ct_id = _this.commentId//文章id
                                a.hf_id = _this.repleHf_id//评论id
                                a.type = _this.repleType//1回复评论    2回复用户回复
                                a.commentNum = 0
                                a.like = 0
                                a.inputShow = false

                                _this.comments[_this.index].reply.push(a)
                                _this.replyComment = ''
                                document.getElementsByClassName("reply-comment-input")[_this.index].innerHTML = ""
                                break;
                            case 2000:
                                _this.showError("error", resdata.msg + "，请重新输入");
                                break;
                        }
                    });
                }
            }
            else {
                _this.PayOpen()
            }
        }, 2000),
        //取消回复一级评论
        cancelSendComment() {
            this.btnShow = false
            this.replyComment = ''
            this.comments[this.index].inputShow = false
            this.hideReplyBtn()
            let input = document.getElementById('replyInput')
            input.innerHTML = '';
        },
        //取消回复二级级评论
        cancelSeSendComment() {
            //this.btnShow = false
            this.replyComment = ''
            this.comments[this.index].inputShow = false
            document.getElementsByClassName("reply-comment-input")[this.index].innerHTML = ""
        },
        onDivInput: function (e) {
            this.replyComment = e.target.innerHTML;
        },
        dateStr(date) {
            //获取js 时间戳
            var time = new Date().getTime();
            //去掉 js 时间戳后三位，与php 时间戳保持一致
            time = parseInt((time - date) / 1000);
            //存储转换值 
            var s;
            if (time < 60 * 10) {//十分钟内
                return '刚刚';
            } else if ((time < 60 * 60) && (time >= 60 * 10)) {
                //超过十分钟少于1小时
                s = Math.floor(time / 60);
                return s + "分钟前";
            } else if ((time < 60 * 60 * 24) && (time >= 60 * 60)) {
                //超过1小时少于24小时
                s = Math.floor(time / 60 / 60);
                return s + "小时前";
            } else if ((time < 60 * 60 * 24 * 30) && (time >= 60 * 60 * 24)) {
                //超过1天少于30天内
                s = Math.floor(time / 60 / 60 / 24);
                return s + "天前";
            } else {
                //超过30天ddd
                var date = new Date(parseInt(date));
                return date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + date.getDate();
            }
        },
        //热点和精推权限检测
        PayOpen() {
            this.$confirm('登录之后才能评论, 是否登录?', '评论管理', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                this.$router.push("/MyPayA")
                // this.$message({
                //     type: 'success',
                //     message: '删除成功!'
                // });
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });
            });
        },
        //空格处理  换行处理
        myReplace(f, e) {
            var reg = new RegExp(f, "g"); //创建正则RegExp对象   
            return this.replace(reg, e);
        },
        //消息提示
        showError(type, status) {
            this.$message({
                type: type,
                showClose: true,
                center: true,
                message: status
            });
        },
    },
}
</script>
<style lang="scss" scoped>
.my-top {
    height: 40px;
    width: 100%;
    background: #f6f6f6;
    font-size: 18px;
    text-align: center;
    line-height: 40px;
    margin: 10px 0;
}
.my-reply {
    padding: 10px;
    background-color: #fafbfc;
    .header-img {
        display: inline-block;
        vertical-align: top;
    }
    .reply-info {
        display: inline-block;
        margin-left: 5px;
        width: 80%;
        @media screen and (max-width: 1200px) {
            width: 80%;
        }
        .reply-input {
            min-height: 20px;
            line-height: 22px;
            padding: 10px 10px;
            color: #ccc;
            background-color: #fff;
            border-radius: 5px;
            &:empty:before {
                content: attr(placeholder);
            }
            &:focus:before {
                content: none;
            }
            &:focus {
                padding: 8px 8px;
                border: 2px solid blue;
                box-shadow: none;
                outline: none;
                color: #333;
            }
        }
    }

    .reply-info-se {
        display: inline-block;
        margin-left: 5px;
        width: 78%;
        @media screen and (max-width: 1200px) {
            width: 80%;
        }
        .reply-input {
            min-height: 20px;
            line-height: 22px;
            padding: 10px 10px;
            color: #ccc;
            background-color: #fff;
            border-radius: 5px;

            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;

            &:empty:before {
                content: attr(placeholder);
            }
            &:focus:before {
                content: none;
            }
            &:focus {
                padding: 8px 8px;
                border: 2px solid blue;
                box-shadow: none;
                outline: none;
                color: #333;
            }
        }
    }
    .reply-btn-box {
        height: 25px;
        margin: 4px 0 10px 0;
        float: right;
        .reply-btn {
            position: relative;
            float: right;
            margin-right: 15px;
        }
    }
}

.my-comment-reply {
    margin-left: 50px;
    .reply-input {
        width: flex;
    }
}

.author-title:not(:last-child) {
    border-bottom: 1px solid rgba(178, 186, 194, 0.3);
}

.author-title {
    padding: 10px;
    .header-img {
        display: inline-block;
        vertical-align: top;
    }
    .author-info {
        display: inline-block;
        margin-left: 5px;
        width: 60%;
        height: 50px;
        line-height: 20px;

        > span {
            display: block;
            // cursor: pointer;
            overflow: hidden;
            white-space: normal;
            text-overflow: ellipsis;
        }
        .author-name {
            color: #000;
            font-size: 18px;
            font-weight: bold;
            line-height: 30px;
        }
        .author-time {
            font-size: 14px;
        }
    }
    .icon-btn {
        height: 50px;
        line-height: 50px;

        width: 8%;
        padding: 0 !important ;
        float: right;
        @media screen and (max-width: 1200px) {
            width: 20%;
            padding: 7px;
        }
        > span {
            //margin-top: 10px;
            cursor: pointer;
        }
        .iconfont {
            margin: 0 5px;
        }

        .add-border {
            position: relative;
            font-size: 22px;
            width: 80px;
            height: 40px;
            border: none;
            background: #ffffff;
            padding-top: 10px;
            line-height: 10px;
            text-align: left;
            .add-font span {
                line-height: 10px;
            }

            .add-listname {
                position: absolute;
                top: 10px;
                left: 40px;
                margin-top: 5px;
                font-size: 13px;
                float: left;
            }
        }
        .add-border /deep/ .el-button {
            border: none;
        }

        .add-border-reply {
            position: relative;
            font-size: 22px;
            width: 80px;
            height: 40px;
            border: none;
            background: #efefef;
            padding-top: 10px;
            line-height: 10px;
            text-align: left;

            .add-font span {
                line-height: 10px;
            }

            .add-listname {
                position: absolute;
                top: 10px;
                left: 40px;
                margin-top: 5px;
                font-size: 13px;
                float: left;
            }
        }
        .add-border-reply /deep/ .el-button {
            border: none;
            background: #efefef;
        }
    }

    .talk-box {
        margin: 0 0px 0 50px;
        background: #efefef;
        > p {
            padding-left: 15px;
            padding-right: 15px;
            margin: 0;

            text-align: left;
            //overflow: hidden;
        }
        .reply {
            font-size: 16px;
            color: #000;

            > div {
                height: 0;
                display: none;
            }

            word-wrap: break-word;
        }
    }
    .reply-box {
        margin: 10px 0 0 50px;
        background: #efefef;
    }
}
</style>

